<template>
  <div class="home-view">
    <div
v-if="loading" class="loading">加载中...</div>
    <div v-else>
      <div v-if="user"
class="user-info">
        <img
:src="user.avatar || '@/assets/default-avatar.png'" alt="用户头像" />
        <h1>欢迎回来，{{ user.nickname || user.username }}</h1>
        <p>上次登录时间：{{ formatDate(user.lastLoginTime) }}</p>
      </div>
      <button :disabled="loggingOut"
@click="handleLogout">
        {{ loggingOut ? '退出中...' : '退出登录' }}
      </button>
    </div>
    <div v-if="error"
class="error">
      {{ error }}
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import { getUserInfo, logout } from '@/services/user'

  const router = useRouter()
  const user = ref(null)
  const loading = ref(true)
  const loggingOut = ref(false)
  const error = ref('')

  onMounted(async () => {
    try {
      const data = await getUserInfo()
      user.value = data
      localStorage.setItem('user', JSON.stringify(data))
    } catch (err) {
      error.value = '获取用户信息失败'
      console.error(err)
    } finally {
      loading.value = false
    }
  })

  const formatDate = timestamp => {
    if (!timestamp) return '未知'
    return new Date(timestamp).toLocaleString()
  }

  const handleLogout = async () => {
    try {
      loggingOut.value = true
      await logout()
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      router.push('/login')
    } catch (err) {
      error.value = '退出登录失败'
      console.error(err)
    } finally {
      loggingOut.value = false
    }
  }
</script>

<style scoped>
  .home-view {
    padding: 20px;
    text-align: center;
  }

  .user-info {
    margin-bottom: 30px;
  }

  .user-info img {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    margin-bottom: 15px;
  }

  .loading,
  .error {
    margin: 20px 0;
    color: #666;
  }

  .error {
    color: #f56c6c;
  }

  button {
    margin-top: 20px;
    padding: 8px 16px;
    background: #f56c6c;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
  }

  button:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
</style>
